/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.empty() == true) return nullptr;

        int val = preorder[0];
        vector<int>::iterator index = find(inorder.begin(), inorder.end(), val);

        vector<int> inoderLeft, inoderRight, preorderLeft, preorderRight;
        inoderLeft.assign(inorder.begin(), index);
        inoderRight.assign(index + 1, inorder.end());
        preorderLeft.assign(preorder.begin() + 1, preorder.begin() + inoderLeft.size() + 1);
        preorderRight.assign(preorder.begin() + inoderLeft.size() + 1, preorder.end());

        // coutVector(inoderLeft);
        // coutVector(inoderRight);
        // coutVector(preorderLeft);
        // coutVector(preorderRight);

        TreeNode* root = new TreeNode(val);
        root->left = buildTree(preorderLeft, inoderLeft);
        root->right = buildTree(preorderRight, inoderRight);


        return root;
    }

    void coutVector(vector<int>& vector){
        for(auto item : vector){
            cout << item << " ";
        }
        cout << endl;
    }
};